package com.shortlink.auth.interceptor;

import com.shortlink.auth.util.JwtUtils;
import com.shortlink.common.constant.HeaderConstant;
import com.shortlink.common.user.UserContext;
import com.shortlink.common.user.UserInfoDTO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * Token解析全局拦截器
 *
 * @author wp
 */
@Component
@RequiredArgsConstructor
public class TokenInterceptor implements HandlerInterceptor {
    private final JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable Object handler) {
        String token = request.getHeader(HeaderConstant.AUTHORIZATION);
        UserInfoDTO userInfoDTO = jwtUtils.parseToken(token);
        UserContext.setUser(userInfoDTO);
        return true;
    }
}
